package com.demo.common.aspect;

import com.demo.common.annotation.Clog;
import com.demo.common.domain.ClogDto;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.util.Date;

/**
 *
 * @author luoguoqiang
 * @since 2021/2/3
 */
@Aspect
@Component
@Slf4j
public class ClogImpl {

  @Around("@annotation(com.demo.common.annotation.Clog)")
  public Object logImpl(ProceedingJoinPoint joinPoint) throws Throwable {
    //获取方法参数值数组
    Object[] args = joinPoint.getArgs();
    /**
     * 1  打印详细的日志
     * 2. 计算执行时间
     * 3. 异常处理以及信息打印
     */
    ClogDto clogDto = new ClogDto();
    Class<?> targetCls = joinPoint.getTarget().getClass();
    clogDto.setClassName(targetCls.getTypeName());
    //得到其方法签名
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    clogDto.setMethodName(methodSignature.getName());
    //获取注解属性
    Clog clog = methodSignature.getMethod().getAnnotation(Clog.class);
    clogDto.setDesc(clog.descrption());
    //开始时间
    clogDto.setBeginDate(new Date());
    clogDto.setBeginTimeMillis( System.currentTimeMillis());
    //参数列表
    clogDto.setParamList(args);
    //执行前打印信息
    log.info("{}",clogDto.toString());
    Object result = null;
    try {
      result = joinPoint.proceed(args);
      clogDto.setReturnObj(result);
    } catch (Exception e){
      log.info("{}", e);
    } finally {
      clogDto.setEndDate(new Date());
      clogDto.setEndTimeMillis(System.currentTimeMillis());
      log.info("{}",clogDto.toString());
    }
    //如果这里不返回result，则目标对象实际返回值会被置为null
    return result;
  }



}


